import axios from 'axios'

// 体彩API配置
const SPORTTERY_API = {
  baseURL: 'https://webapi.sporttery.cn/gateway/uniform/football',
  timeout: 15000,
  retry: 3, // 重试次数
  retryDelay: 1000 // 重试延迟(ms)
}

// 创建axios实例
const sportteryClient = axios.create(SPORTTERY_API)

// 重试机制
const retryRequest = (config, retryCount = 0) => {
  return new Promise((resolve, reject) => {
    const retry = () => {
      sportteryClient(config)
        .then(resolve)
        .catch(error => {
          if (retryCount < SPORTTERY_API.retry) {
            console.log(`体彩API请求失败，正在重试... (${retryCount + 1}/${SPORTTERY_API.retry})`)
            setTimeout(() => {
              retryRequest(config, retryCount + 1).then(resolve).catch(reject)
            }, SPORTTERY_API.retryDelay * (retryCount + 1))
          } else {
            reject(error)
          }
        })
    }
    retry()
  })
}

// 请求拦截器
sportteryClient.interceptors.request.use(
  config => {
    // 添加必要的请求头
    config.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    config.headers['Accept'] = 'application/json, text/plain, */*'
    config.headers['Accept-Language'] = 'zh-CN,zh;q=0.9,en;q=0.8'
    config.headers['Referer'] = 'https://www.sporttery.cn/'
    config.headers['Origin'] = 'https://www.sporttery.cn'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
sportteryClient.interceptors.response.use(
  response => {
    // 处理体彩API的响应格式
    if (response.data && response.data.value) {
      return response.data
    }
    return response
  },
  error => {
    console.error('体彩API请求失败:', error)
    // 如果是网络错误，尝试重试
    if (error.code === 'ECONNABORTED' || error.code === 'ENOTFOUND' || error.code === 'ECONNRESET') {
      return retryRequest(error.config)
    }
    return Promise.reject(error)
  }
)

// 获取赛事列表
export function getSportteryMatches(params = {}) {
  return sportteryClient.get('/getMatchCalculatorV1.qry', {
    params: Object.assign({
      poolCode: params.poolCode || '',
      channel: params.channel || 'c'
    }, params)
  }).then(response => {
    // 验证响应数据
    if (!response || !response.value) {
      throw new Error('体彩API返回数据格式错误')
    }

    return response
  }).catch(error => {
    console.error('获取体彩赛事列表失败:', error)

    // 返回默认的空数据结构
    return {
      value: {
        matchInfoList: [],
        leagueInfo: []
      }
    }
  })
}

// 获取联赛列表
export function getSportteryLeagues() {
  return sportteryClient.get('/getLeagueListV1.qry', {
    params: {
      channel: 'c'
    }
  }).then(response => {
    return response
  }).catch(error => {
    console.error('获取体彩联赛列表失败:', error)
    throw error
  })
}

// 获取赔率信息
export function getSportteryOdds(matchId) {
  return sportteryClient.get('/getOddsV1.qry', {
    params: {
      matchId,
      channel: 'c'
    }
  }).then(response => {
    return response
  }).catch(error => {
    console.error('获取体彩赔率失败:', error)
    throw error
  })
}

// 解析体彩赛事数据
export function parseSportteryMatchData(sportteryData) {
  const matches = []

  try {
    if (sportteryData && sportteryData.value && sportteryData.value.matchInfoList) {
      // 处理体彩API返回的数据结构 - matchInfoList是对象数组，每个对象包含subMatchList字段
      const matchList = []
      sportteryData.value.matchInfoList.forEach(leagueGroup => {
        if (leagueGroup.subMatchList && Array.isArray(leagueGroup.subMatchList)) {
          matchList.push(...leagueGroup.subMatchList)
        }
      })

      matchList.forEach(match => {
        // 解析比赛时间
        console.log(match)
        let matchTime = new Date().toISOString()

        if (match.matchDate && match.matchTime) {
          // 处理日期格式，确保格式正确
          const dateStr = match.matchDate
          const timeStr = match.matchTime

          // 如果日期格式是 YYYY-MM-DD，直接使用
          if (dateStr.includes('-')) {
            matchTime = new Date(`${dateStr} ${timeStr}`).toISOString()
          } else {
            // 如果是其他格式，尝试解析
            try {
              matchTime = new Date(`${dateStr} ${timeStr}`).toISOString()
            } catch (e) {
              console.warn('时间解析失败:', dateStr, timeStr, e)
              matchTime = new Date().toISOString()
            }
          }
        }

        // 解析赔率数据 - 从had对象获取胜平负赔率
        const had = match.had || {}
        const winOdds = had.h ? parseFloat(had.h) : 0
        const drawOdds = had.d ? parseFloat(had.d) : 0
        const loseOdds = had.a ? parseFloat(had.a) : 0

        const parsedMatch = {
          sporttery_id: match.matchId || '',
          league: match.leagueAbbName || '未知联赛',
          home_team: match.homeTeamAbbName || '主队',
          away_team: match.awayTeamAbbName || '客队',
          match_time: matchTime,
          status: getMatchStatus(match.sellStatus),
          win_odds: winOdds,
          draw_odds: drawOdds,
          lose_odds: loseOdds,

          // 扩展字段
          home_team_id: match.homeTeamId || '',
          away_team_id: match.awayTeamId || '',
          league_id: match.leagueId || '',
          match_date: match.matchDate || '',
          week_day: match.weekDay || '',
          match_num: match.matchNum || '',
          matchNumStr: match.matchNumStr || '',

          // 比分信息
          home_score: parseInt(match.homeScore) || 0,
          away_score: parseInt(match.awayScore) || 0,
          home_half_score: parseInt(match.homeHalfScore) || 0,
          away_half_score: parseInt(match.awayHalfScore) || 0,

          // 其他赔率信息
          hhad: match.hhad || {}, // 让球胜平负
          hafu: match.hafu || {}, // 半全场
          crs: match.crs || {}, // 比分
          ttg: match.ttg || {}, // 进球数

          // 时间戳
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }
        console.log(parsedMatch)
        // 只添加有效的比赛数据
        if (parsedMatch.sporttery_id && parsedMatch.home_team && parsedMatch.away_team) {
          matches.push(parsedMatch)
        }
      })
    }
  } catch (error) {
    console.error('解析体彩数据失败:', error)
  }

  return matches
}

// 获取比赛状态
function getMatchStatus(status) {
  const statusMap = {
    '0': 'upcoming', // 未开始
    '1': 'live', // 进行中
    '2': 'finished', // 已结束
    '3': 'cancelled', // 已取消
    'Selling': 'upcoming', // 销售中 - 未开始
    'Live': 'live', // 进行中
    'Finished': 'finished', // 已结束
    'Cancelled': 'cancelled' // 已取消
  }
  return statusMap[status] || 'upcoming'
}

// 获取联赛名称映射
export function getLeagueNameMapping() {
  return {
    '1': '英超',
    '2': '西甲',
    '3': '德甲',
    '4': '意甲',
    '5': '法甲',
    '6': '欧冠',
    '7': '欧联',
    '8': '中超',
    '9': '日职',
    '10': '韩职'
  }
}

// 同步体彩数据到本地
export function syncSportteryDataToLocal() {
  // 1. 获取体彩数据
  return getSportteryMatches().then(sportteryData => {
    // 2. 解析数据
    const matches = parseSportteryMatchData(sportteryData)

    // 3. 这里应该调用后端API保存到数据库
    // 暂时返回解析后的数据
    return {
      success: true,
      data: matches,
      count: matches.length
    }
  }).catch(error => {
    console.error('同步体彩数据失败:', error)
    return {
      success: false,
      error: error.message
    }
  })
}

export default {
  getSportteryMatches,
  getSportteryLeagues,
  getSportteryOdds,
  parseSportteryMatchData,
  syncSportteryDataToLocal
}
